import 'dart:convert';

import 'icon.dart';

enum IconExportType {
  css,
  dart,
}

Future<List<int>> exportIcons(
    String preName, Iterable<IconItem> codeMap, IconExportType type) async {
  late String content;
  switch (type) {
    case IconExportType.dart:
      content = _exportDart(preName, codeMap);
      break;
    case IconExportType.css:
      content = _exportCss(preName, codeMap);
  }
  return utf8.encode(content);
}

String _exportCss(String preName, Iterable<IconItem> codeMap) {
  StringBuffer cssFile = StringBuffer();
  cssFile.writeln("""@font-face {
  font-family: "$preName-icon";
  src: url('$preName.ttf?t=1506391926153') format('truetype');
}
  """);
  cssFile.writeln(""".$preName {
  font-family:"$preName-icon" !important;
  font-size:16px;
  font-style:normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}""");
  for (IconItem item in codeMap) {
    cssFile.writeln(
        '.$preName-${item.name}:before { content: "${item.code.replaceFirst('0x', '\\')}"; }');
  }

  return cssFile.toString();
}

String _exportDart(String preName, Iterable<IconItem> codeMap) {
  StringBuffer dartFile = StringBuffer();
  String classPrefix = preName
      .replaceAllMapped(RegExp(r'(^|_)([a-z])', caseSensitive: false), (match) {
    return match[2]!.toUpperCase();
  });
  dartFile.writeln("import 'package:flutter/widgets.dart';\n");
  dartFile.writeln('class ${classPrefix}Icons {');
  dartFile.writeln('  static const _icoFont = \'${preName.toLowerCase()}\';');
  for (IconItem item in codeMap) {
    final name = item.name
        .replaceAll('-', '_')
        .replaceFirstMapped(RegExp(r'^\d'), (match) => '\$${match.input}')
        .replaceAllMapped(
          RegExp('_([a-z])'),
          (match) => match.group(1)!.toUpperCase(),
        );
    dartFile.writeln(
        '  static const $name = IconData(${item.code}, fontFamily: _icoFont);');
  }
  dartFile.writeln('}');

  return dartFile.toString();
}
